package com.zhxymm.book.controllers;

import com.zhxymm.book.dao.BorrowRepository;
import com.zhxymm.book.entity.Borrow;
import com.zhxymm.book.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("borrows")
public class BorrowController {

    @Autowired
    BorrowService borrowService;

    @Autowired
    BorrowRepository borrowRepository;

    @GetMapping
    public String displayBorrows(Model model){

        List<Borrow> borrows = borrowService.getAll();
        model.addAttribute("borrows",borrows);
        return "borrows/list-borrows";
    }


    @GetMapping("/new")
    public String displayBorrowForm(Model model){

        Borrow aBorrow = new Borrow();
        model.addAttribute("borrow",aBorrow);
        return "borrows/new-borrow";
    }

    @PostMapping("/save")
    public String createBorrow(Model model,Borrow borrow){

        borrowService.save(borrow);
        return "redirect:/borrows";
    }

    @GetMapping("/update")
    public String displayBorrowUpdateForm(@RequestParam("id") long theId,Model model){

        Borrow theBorrow = borrowService.findByBookId(theId);
        model.addAttribute("borrow",theBorrow);
        return "borrows/new-borrow";
    }

    @GetMapping("/delete")
    public String deleteBorrow(@RequestParam("id") long theId,Model model){
        Borrow theBorrow = borrowService.findByBookId(theId);
        borrowRepository.delete(theBorrow);
        return "redirect:/borrows";
    }
}